#### Script to do multiple treeMI imputations for the processed ice industry (1977-1997)
### and export the imputed dataset

#### input files:
####	icepf_gooddata.csv
####
#### output files:
####    icep_imputes.csv
####    icep_predicted.csv

require(tree)

#### read in the "good" dataset, in which we have replaced the Census Bureau imputes/edits with missing values
icep_gooddata<-read.csv("icepf_gooddata.csv",header=TRUE)

### Create completed datasets using treeMI:

icep_imputes<-treeMI(icep_gooddata,ITER=5,c(1,0,0,0,0,0,0,0,1,0,0,0,0,0),starter=TRUE,PPDdraw = TRUE, minCut = 5,minDev  = 0.000001, startCut = 5, startDev = 0.000001) 

icep_imputes$impSet$impsetnum <- 1
icep_imputes$PPDsample$impsetnum <- 1

### For the first imputed dataset, create a new file
write.table(icep_imputes$impSet,file="icep_imputes.csv",append=FALSE,sep=",") 
write.table(icep_imputes$PPDsample,file="icep_predicted.csv",append=FALSE,sep=",") 

for (j in 2:500) {

  icep_imputes<-treeMI(icep_gooddata,ITER=5,c(1,0,0,0,0,0,0,0,1,0,0,0,0,0),starter=TRUE,PPDdraw = TRUE, minCut = 5,minDev  = 0.000001, startCut = 5, startDev = 0.000001) 

  icep_imputes$impSet$impsetnum <- j
  icep_imputes$PPDsample$impsetnum <- j

  ### Append the subsequent imputed datasets to the file created for the first dataset

  write.table(icep_imputes$impSet,file="icep_imputes.csv",append=TRUE,sep=",",col.names=FALSE) 
  write.table(icep_imputes$PPDsample,file="icep_predicted.csv",append=TRUE,sep=",",col.names=FALSE) 

}


